package cn.itcast.service.system.impl;

import cn.itcast.dao.system.ModuleDao;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.Role;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ModuleServiceImpl implements ModuleService {

    @Autowired
    private ModuleDao moduleDao;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<Module> findAll() {
        return moduleDao.findAll();
    }

    @Override
    public void save(Module module) {
        moduleDao.save(module);
    }

    @Override
    public Module findById(String id) {
        return moduleDao.findById(id);
    }

    @Override
    public void update(Module module) {
        moduleDao.updateById(module);
    }

    @Override
    public void deleteById(String id) {
        moduleDao.deleteById(id);
    }

    @Override
    public PageInfo<Module> findPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Module> list = moduleDao.findAll();
        return new PageInfo<Module>(list,5);  //第二个参数页面上显示几个页码  默认8

    }

    @Override
    public List<String> findModulsIdsByRoleId(String roleid) {
//        SELECT module_id from pe_role_module where role_id='b3d950e8-05c9-484d-b394-1bb171e92d6d'
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();

        List<String> modulsIdsByRoleId = (List<String>) valueOperations.get(roleid);
        if (modulsIdsByRoleId!=null&&modulsIdsByRoleId.size()!=0){
            System.out.println(modulsIdsByRoleId);
            return modulsIdsByRoleId;
        }else {
            modulsIdsByRoleId = moduleDao.findModulsIdsByRoleId(roleid);
            valueOperations.set(roleid,modulsIdsByRoleId);
            System.out.println(modulsIdsByRoleId);
            return modulsIdsByRoleId;
        }
    }
    @Override
    public List<Module> findModuleListByUser(User user) {
        List<Module> moduleList = null;
        if(user.getDegree()==0){
//            SaaS管理员  select * from ss_module where belong=0
            moduleList =  moduleDao.findByBelong(0);
        }else if(user.getDegree()==1){
//            企业的管理员  select * from ss_module where belong=1
            moduleList =  moduleDao.findByBelong(1);
        }else{ //普通员工
//            涉及到5表联查
            moduleList =  moduleDao.findByUserId(user.getId());
        }
        return moduleList;
    }
}
